package summary

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"oa-rest/common"
	"time"

	"github.com/gin-gonic/gin"
)

// SummaryResponse 文档总结响应结构
type SummaryResponse struct {
	Filename      string  `json:"filename"`
	Summary       string  `json:"summary"`
	ContentLength int64   `json:"content_length"`
	SummaryLength int     `json:"summary_length"`
}

// SummaryService 文档总结服务
type SummaryService struct {
	summaryClient *common.Client
}

// NewSummaryService 创建文档总结服务
func NewSummaryService() *SummaryService {
	return &SummaryService{
		summaryClient: common.NewClient("http://60.208.118.42:30033"),
	}
}

// UploadAndSummaryHandler 上传文档并获取总结
func (s *SummaryService) UploadAndSummaryHandler(c *gin.Context) {
	// 获取上传的文件
	file, header, err := c.Request.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "获取上传文件失败: " + err.Error(),
			"data":    nil,
		})
		return
	}
	defer file.Close()

	// 读取文件内容到内存
	buffer := make([]byte, header.Size)
	_, err = file.Read(buffer)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "读取文件内容失败: " + err.Error(),
			"data":    nil,
		})
		return
	}

	// 调用外部文档总结服务
	summaryResp, err := s.callSummaryService(header.Filename, buffer)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "调用文档总结服务失败: " + err.Error(),
			"data":    nil,
		})
		return
	}

	// 返回总结结果
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "文档总结处理成功",
		"data":    summaryResp,
	})
}

// callSummaryService 调用外部文档总结服务
func (s *SummaryService) callSummaryService(filename string, fileData []byte) (*SummaryResponse, error) {
	// 创建multipart表单
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)

	// 添加文件字段
	part, err := writer.CreateFormFile("file", filename)
	if err != nil {
		return nil, fmt.Errorf("创建表单文件失败: %w", err)
	}

	// 写入文件数据
	_, err = part.Write(fileData)
	if err != nil {
		return nil, fmt.Errorf("写入文件数据失败: %w", err)
	}

	// 关闭writer
	err = writer.Close()
	if err != nil {
		return nil, fmt.Errorf("关闭表单writer失败: %w", err)
	}

	// 创建HTTP请求
	url := "http://60.208.118.42:30033/upload"
	req, err := http.NewRequest("POST", url, body)
	if err != nil {
		return nil, fmt.Errorf("创建HTTP请求失败: %w", err)
	}

	// 设置请求头
	req.Header.Set("Content-Type", writer.FormDataContentType())
	req.Header.Set("Accept", "application/json")

	// 设置超时时间
	client := &http.Client{
		Timeout: 120 * time.Second, // 2分钟超时，文档处理可能需要较长时间
	}

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("发送HTTP请求失败: %w", err)
	}
	defer resp.Body.Close()

	// 检查响应状态码
	if resp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(resp.Body)
		return nil, fmt.Errorf("文档总结服务返回错误状态码: %d, 响应: %s", resp.StatusCode, string(body))
	}

	// 读取响应体
	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("读取响应体失败: %w", err)
	}

	// 解析JSON响应
	var summaryResp SummaryResponse
	err = json.Unmarshal(respBody, &summaryResp)
	if err != nil {
		return nil, fmt.Errorf("解析JSON响应失败: %w", err)
	}

	return &summaryResp, nil
}

// RegisterRoutes 注册路由
func (s *SummaryService) RegisterRoutes(router *gin.RouterGroup) {
	summaryGroup := router.Group("/summary")
	{
		summaryGroup.POST("/upload", s.UploadAndSummaryHandler)
	}
}